<template>
  <div class="sellContainer" :style="conStyle">
    <el-form
      :model="bookForm"
      :rules="bookRules"
      ref="bookRef"
      label-width="150px"
    >
      <el-form-item label="图书名称" prop="book_name">
        <el-input v-model="bookForm.book_name" style="width:80%;"></el-input>
      </el-form-item>
      <el-form-item label="图书作者" prop="book_author">
        <el-input v-model="bookForm.book_author" style="width:80%;"></el-input>
      </el-form-item>
      <el-form-item label="图书出版社" prop="book_press">
        <el-input v-model="bookForm.book_press" style="width:80%;"></el-input>
      </el-form-item>
      <el-form-item label="图书分类" prop="book_category_id">
        <el-select
          v-model="bookForm.book_category_id"
          placeholder="请选择图书分类"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.category_id"
            :label="item.category_name"
            :value="item.category_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图书原价" prop="book_price_yuanjia">
        <el-input
          v-model="bookForm.book_price_yuanjia"
          style="width:80%;"
        ></el-input>
      </el-form-item>
      <el-form-item label="图书售价" prop="book_price_xianjia">
        <el-input
          v-model="bookForm.book_price_xianjia"
          style="width:80%;"
        ></el-input>
      </el-form-item>
      <el-form-item label="图书封面" prop="book_cover">
        <!-- 商品图片上传
    action:指定图片上传api接口
    :on-preview ： 当点击图片时会触发该事件进行预览操作,处理图片预览
    :on-remove : 当用户点击图片右上角的X号时触发执行
    :on-success：当用户点击上传图片并成功上传时触发
    list-type ：设置预览图片的方式
    :headers ：设置上传图片的请求头 -->
        <el-upload
          :action="uploadURL"
          ref="uploadImg"
          :on-preview="handlePreview"
          :before-upload="beforeUpload"
          :on-remove="handleRemove"
          :on-change="handleChange"
          :on-success="handleSuccess"
          list-type="picture-card"
          :auto-upload="false"
          :limit="1"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="出售数量" prop="book_num">
        <el-input-number
          v-model="bookForm.book_num"
          :min="1"
          :max="10"
          size="mini"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="图书备注" prop="book_remarks">
        <el-input type="textarea" v-model="bookForm.book_remarks"></el-input>
      </el-form-item>
    </el-form>
    <el-button size="small" type="primary" @click="upload">点击发布</el-button>

    <!-- 图片显示 -->
    <el-dialog :visible.sync="imageDialogVisible">
      <img width="100%" :src="imageDialogUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      conStyle: {
        width: '500px',
        padding: '10px 50px',
        background: 'url(' + require('../../assets/images/sellbg.jpg') + ')',
        backgroundSize: '100% 100%',
        backgroundRepeat: 'no-repeat',
        boxShadow: '-10px -10px 10px rgba(0, 0, 0, 0.3)'
      },
      // 提交表单
      bookForm: {
        book_name: '', // 书名
        book_author: '', // 作者
        book_press: '', // 出版社
        book_category_id: '', // 分类id
        book_price_yuanjia: '', // 书原价
        book_price_xianjia: '', // 书现价
        book_cover: '', // 封面地址
        book_num: '', // 出售数量
        book_remarks: '', // 备注
        book_seller: ''
      },
      // 下拉框数据
      categoryList: [],
      // 表单规则
      bookRules: {
        book_name: [
          { required: true, message: '请输入图书名称', trigger: 'blur' }
        ],
        book_author: [
          { required: true, message: '请输入图书作者', trigger: 'blur' }
        ],
        book_press: [
          { required: true, message: '请输入图书出版社', trigger: 'blur' }
        ],
        book_category_id: [
          { required: true, message: '请选择图书分类', trigger: 'change' }
        ],
        book_price_yuanjia: [
          { required: true, message: '请输入图书原价', trigger: 'blur' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确的格式,可保留两位小数'
          }
        ],
        book_price_xianjia: [
          { required: true, message: '请输入图书原价', trigger: 'blur' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确的格式,可保留两位小数'
          }
        ],
        book_cover: [
          { required: true, message: '请上传图书封面', trigger: 'change' }
        ],
        book_remarks: [
          {
            required: true,
            message: '请输入图书备注（例如:五成新）',
            trigger: 'blur'
          }
        ]
      },
      // 图片上传地址
      uploadURL: 'http://127.0.0.1:3000/api/upload/images',
      // 图片预览框
      imageDialogUrl: '',
      imageDialogVisible: false
    }
  },
  mounted() {
    this.getCategory()
  },
  methods: {
    // 获取图书分类
    async getCategory() {
      const { data: res } = await this.$http.get('/category/getCategory')
      if (res.status !== 200) return this.$message.error('获取分类列表失败')
      else {
        this.categoryList = res.data
      }
      // console.log(this.categoryList)
    },
    // 图片上传前判断
    beforeUpload(file) {
      const isJPG = ~['image/jpeg', 'image/png'].indexOf(file.type)
      const isLt3M = file.size / 1024 / 1024 < 3

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG和PNG 格式!')
      }

      if (!isLt3M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }
      return isJPG && isLt3M
    },
    // 当点击图片时会触发该事件进行预览操作,处理图片预览
    handlePreview(file) {
      this.imageDialogUrl = file.url
      this.imageDialogVisible = true
    },
    // 图片改变
    handleChange(file, fileList) {
      console.log(fileList.length)
      if (fileList.length !== 0) {
        this.bookRules.book_cover = []
      }
    },
    // 图片删除
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.bookRules.book_cover = [
          { required: true, message: '请上传图书封面', trigger: 'change' }
        ]
      }
    },
    // 点击按钮发布图书
    upload() {
      this.$refs.bookRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请输入完整信息')
        } else {
          // 上传图片
          this.$refs.uploadImg.submit()
        }
      })
    },
    // 当用户上传图片成功上传时触发
    async handleSuccess(res, file) {
      res.path = res.path.replaceAll('\\', '/')
      console.log(res.path)
      this.bookForm.book_cover = res.path
      this.bookForm.book_date = this.getNowFormatDate()
      this.bookForm.book_seller = this.getUser
      console.log(this.bookForm)
      const result = await this.$http.post('upload/book', this.bookForm)
      if (result.status !== 200) return this.$message.error('上传失败')
      else {
        console.log(result)
        this.$message.success('上传成功')
        this.$refs.bookRef.resetFields()
        this.$refs.uploadImg.clearFiles()
      }
    }
  },
  computed: {
    ...mapGetters('user', ['getUser'])
  }
}
</script>

<style lang="scss" scoped>
.sellContainer {
  margin: 0 auto;
  .el-button {
    margin-left: 150px;
    background-color: #d2ac6b;
    color: #fff;
    font-size: 15px;
    font-weight: bold;
    border-radius: 0px;
  }
  /deep/ .el-input__inner {
    height: 30px;
  }
}
</style>
